package logic

import (
	"context"
	"errors"
	"math/rand"
	"renting-demo/model/mysql"
	"time"

	"renting-demo/houseorder_srv/houseorder"
	"renting-demo/houseorder_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *houseorder.CreateOrderRequest) (*houseorder.Response, error) {
	// todo: add your logic here and delete this line
	//生成唯一订单号
	strs := "123467890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	rand.Seed(time.Now().UnixNano())
	b := make([]byte, 10)
	for i := range b {
		b[i] = strs[rand.Intn(len(strs))]
	}
	date := in.Date * 24 * 30 * 3600
	datetime := time.Now().Unix() + date
	res := mysql.CreateHouseOrder(mysql.HouseOrder{
		OrderNumber: string(b),
		UserId:      in.UserID,
		HouseId:     in.HouseId,
		BeginDate:   time.Now(),
		EndDate:     UnixSecondToTime(datetime),
		HousePrice:  in.HousePrice,
		Amount:      in.Amount,
		Status:      "待支付",
	})
	if res.ID == 0 {
		return nil, errors.New("订单创建失败")
	}
	return &houseorder.Response{
		Status: "1",
	}, nil
}
func UnixSecondToTime(second int64) time.Time {
	return time.Unix(second, 0)
}
